COMP3141
Software System Design and Implementation (18s1)

Code (Week 6)

Table of Contents

1 Counter Monad

module Counter where

import Control.Monad.State   

type Counter = State Int


-- get is defined in Control.Monad.State and just
-- returns the currrent state
getCnt :: Counter Int
getCnt = get


-- put is defined in Control.Monad.State and 
-- sets the state to a given value
incCnt :: Counter ()
incCnt = do
  currCnt <- get
  put (currCnt + 1) 


setCnt :: Int -> Counter ()
setCnt = put

runCounterPrg :: Counter a -> a
runCounterPrg prg = fst $ runState prg 0

1.1 Using the Counter Monad

module Main where

import Counter
import Data.Char

countUppercase :: String -> Counter ()
countUppercase [] = return ()
countUppercase (c : restStr) = do
  if isUpper c
    then do incCnt
            countUppercase restStr
    else countUppercase restStr

simpleCounterPrg :: Counter Int
simpleCounterPrg = do
  countUppercase "This iS a compliCaTed PrograM"
  countUppercase "soLVing a sImple Problem"
  getCnt

main = do
  let finalCnt = runCounterPrg simpleCounterPrg
  putStrLn $ "found " ++ 
             show finalCnt  ++ 
             " uppercase letters in the strings"

2 IO Monad

module Main where

import Text.Read  


addIO :: IO ()
addIO = do
  putStrLn "Please enter two integer values:"
  putStr "Value 1: "
  n1 <- readInt
  putStr "Value 2: "
  n2 <- readInt
  putStrLn ("the result of adding " ++ 
            show n1 ++ " and " ++ 
            show n2 ++ " is "  ++ 
            show (n1 + n2))


readInt :: IO Int
readInt = do 
  nStr <- getLine 
  case readMaybe nStr of
    Nothing -> do  putStrLn "invalid input, please try again: "
                   readInt
    Just n  -> return n :: IO Int


main :: IO ()
main = addIO

2018-06-14 Thu 18:28

Announcements RSS